<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { getSalaryPayReviewList, reviewSalaryPay } from '@/api/salary'

const columns = [
  { title: '发放批次', dataIndex: 'batch', key: 'batch', width: 150 },
  { title: '发放月份', dataIndex: 'month', key: 'month', width: 120 },
  { title: '适用机构', dataIndex: 'organization', key: 'organization', width: 150 },
  { title: '适用职位', dataIndex: 'positions', key: 'positions', width: 200 },
  { title: '发放人数', dataIndex: 'count', key: 'count', width: 100 },
  { title: '应发总额', dataIndex: 'totalPay', key: 'totalPay', width: 150 },
  { title: '实发总额', dataIndex: 'actualPay', key: 'actualPay', width: 150 },
  { title: '登记时间', dataIndex: 'registerTime', key: 'registerTime', width: 180 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
  { title: '操作', key: 'action', width: 200 },
]

const dataSource = ref([])
const loading = ref(false)

// 分页相关
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total) => `共 ${total} 条`,
})

const reviewRecord = ref(null)
const reviewVisible = ref(false)
const reviewForm = ref({
  result: null,
  comment: '',
})

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  try {
    const date = new Date(dateTime)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  } catch {
    return dateTime
  }
}

// 获取待复核薪酬发放列表
const fetchReviewList = async (page = 1, pageSize = 10) => {
  loading.value = true
  try {
    const response = await getSalaryPayReviewList({ page, pageSize })

    // 处理返回的数据
    if (response && response.list) {
      dataSource.value = response.list.map((item) => ({
        ...item,
        key: item.id,
        registerTime: formatDateTime(item.registerTime),
      }))
      // 更新分页信息
      pagination.value.total = response.total || 0
      pagination.value.current = response.page || page
      pagination.value.pageSize = response.pageSize || pageSize
    } else {
      dataSource.value = []
      pagination.value.total = 0
    }
  } catch (error) {
    console.error('获取待复核薪酬发放列表失败:', error)
    dataSource.value = []
    pagination.value.total = 0
  } finally {
    loading.value = false
  }
}

// 处理分页变化
const handleTableChange = (pag) => {
  pagination.value.current = pag.current
  pagination.value.pageSize = pag.pageSize
  fetchReviewList(pag.current, pag.pageSize)
}

const handleReview = (record) => {
  reviewRecord.value = record
  reviewVisible.value = true
  reviewForm.value = { result: null, comment: '' }
}

const handleReviewSubmit = async () => {
  if (!reviewForm.value.result) {
    message.warning('请选择复核结果')
    return
  }
  if (reviewForm.value.result === '不通过' && !reviewForm.value.comment) {
    message.warning('请填写不通过原因')
    return
  }

  if (!reviewRecord.value || !reviewRecord.value.id) {
    message.warning('无法获取薪酬发放ID')
    return
  }

  try {
    const response = await reviewSalaryPay(reviewRecord.value.id, {
      result: reviewForm.value.result,
      comment: reviewForm.value.comment || '',
    })

    console.log('薪酬发放复核响应:', response)

    // 根据响应更新状态
    const newStatus =
      response?.status || (reviewForm.value.result === '通过' ? '已生效' : '复核不通过')

    message.success(`复核${reviewForm.value.result}，操作成功`)
    reviewVisible.value = false

    // 更新列表中的状态
    const index = dataSource.value.findIndex((item) => item.key === reviewRecord.value.key)
    if (index !== -1) {
      dataSource.value[index].status = newStatus
      // 如果复核通过，从列表中移除（因为已生效，不再显示在待复核列表中）
      if (newStatus === '已生效') {
        dataSource.value.splice(index, 1)
        // 更新总数
        pagination.value.total = Math.max(0, pagination.value.total - 1)
      }
    }

    // 刷新列表
    fetchReviewList(pagination.value.current, pagination.value.pageSize)
  } catch (err) {
    console.error('复核失败:', err)
    // handleApiError 已经处理了错误提示
  }
}

onMounted(() => {
  fetchReviewList(1, pagination.value.pageSize)
})
</script>

<template>
  <div class="page-container">
    <div class="page-header">
      <h1 class="page-title">薪酬发放复核</h1>
      <p class="page-desc">审核薪酬发放数据的准确性，复核通过后锁定数据，禁止修改</p>
    </div>

    <div class="page-content">
      <div class="table-wrapper">
        <a-table
          :columns="columns"
          :data-source="dataSource"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="['organization'].includes(column.key)">
              <span>{{ record[column.key] || '-' }}</span>
            </template>
            <template v-if="column.key === 'positions'">
              <span>{{ Array.isArray(record.positions) ? record.positions.join('、') : '-' }}</span>
            </template>
            <template v-if="column.key === 'status'">
              <a-tag
                :color="
                  record.status === '待复核'
                    ? 'orange'
                    : record.status === '已生效'
                      ? 'green'
                      : 'red'
                "
              >
                {{ record.status }}
              </a-tag>
            </template>
            <template v-if="['totalPay', 'actualPay'].includes(column.key)">
              <span>¥{{ (record[column.key] || 0).toLocaleString() }}</span>
            </template>
            <template v-if="column.key === 'action'">
              <a-button type="link" size="small" @click="handleReview(record)">复核</a-button>
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <a-modal
      v-model:open="reviewVisible"
      title="薪酬发放复核"
      width="600px"
      @ok="handleReviewSubmit"
    >
      <div class="review-info">
        <p><strong>发放批次：</strong>{{ reviewRecord?.batch || '-' }}</p>
        <p><strong>发放月份：</strong>{{ reviewRecord?.month || '-' }}</p>
        <p><strong>适用机构：</strong>{{ reviewRecord?.organization || '-' }}</p>
        <p>
          <strong>适用职位：</strong
          >{{ Array.isArray(reviewRecord?.positions) ? reviewRecord.positions.join('、') : '-' }}
        </p>
        <p><strong>发放人数：</strong>{{ reviewRecord?.count || 0 }} 人</p>
        <p><strong>应发总额：</strong>¥{{ (reviewRecord?.totalPay || 0).toLocaleString() }}</p>
        <p><strong>实发总额：</strong>¥{{ (reviewRecord?.actualPay || 0).toLocaleString() }}</p>
      </div>
      <div class="review-form">
        <div class="form-item">
          <label>复核结果 <span style="color: red">*</span></label>
          <a-radio-group v-model:value="reviewForm.result">
            <a-radio value="通过">通过</a-radio>
            <a-radio value="不通过">不通过</a-radio>
          </a-radio-group>
        </div>
        <div class="form-item">
          <label>复核意见</label>
          <a-input
            v-model:value="reviewForm.comment"
            type="textarea"
            :rows="4"
            placeholder="请输入复核意见（不通过时必填）"
          />
        </div>
      </div>
    </a-modal>
  </div>
</template>

<style scoped>
.page-container {
  background: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(20px) saturate(180%);
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.04);
}

.page-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1d1d1f;
  margin: 0 0 8px 0;
  letter-spacing: -0.5px;
}

.page-desc {
  font-size: 14px;
  color: #86868b;
  margin: 0;
}

.page-content {
  margin-top: 24px;
}

.table-wrapper {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.02);
}

.review-info {
  background: #f5f5f7;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 24px;
}

.review-info p {
  margin: 8px 0;
  font-size: 14px;
  color: #1d1d1f;
}

.review-form {
  margin-top: 16px;
}

.form-item {
  margin-bottom: 20px;
}

.form-item label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #1d1d1f;
}
</style>
